package cl.sodexo.com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cl.sodexo.com.dao.UsuarioDAO;
import cl.sodexo.com.dto.Usuario;
import cl.sodexo.com.form.LoginForm;
import cl.sodexo.com.utils.Constantes;

/**
 * @author psep
 *
 */
public class LoginAction extends Action{

	private final static Logger logger= Logger.getLogger(LoginAction.class);
	private UsuarioDAO	usuarioDAO;

	/**
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		LoginForm loginFrm	= (LoginForm) form;
		String usuario		= loginFrm.getUser().getUsername();
		HttpSession session = request.getSession(true);
		
		logger.info("user: " + usuario);
		logger.info("session: " + session.getAttribute(Constantes.SESSION));
		
		if(loginFrm.getUser().getUsername() == null || loginFrm.getUser().getUsername().equals("")){
			session.setAttribute(Constantes.SESSION, false);
			session.setAttribute(Constantes.USEROBJ, null);
			return mapping.findForward(Constantes.SUCCESS);
		}else{	
			Usuario	userTO = this.getUsuarioDAO().getUsuario(loginFrm.getUser());
			
			if(userTO == null){
				session.setAttribute(Constantes.SESSION, false);
				session.setAttribute(Constantes.USEROBJ, null);
				return mapping.findForward(Constantes.ERROR);
			}else{
				session.setAttribute(Constantes.SESSION, true);
				session.setAttribute(Constantes.USEROBJ, userTO);
				loginFrm.setUser(userTO);
				return mapping.findForward(Constantes.SESSION);
			}
			
		}
		
	}
	
	/**
	 * @return usuarioDAO
	 */
	private UsuarioDAO getUsuarioDAO(){
		if(this.usuarioDAO == null){
			this.usuarioDAO = new UsuarioDAO();
		}
		
		return this.usuarioDAO;
	}
	
}
